#ifndef gsm_h
#define gsm_h

#include <SoftwareSerial.h>
#include "Arduino.h"

#define SEND_AT_OK 0
#define SEND_AT_NO_ANSWER 1
#define SEND_AT_TIMEOUT 2
#define SEND_AT_ERROR 3

#define ANSWER_LINE_LEN 100

#define WAIT_TIMEOUT 10000

#define ERROR_INCREMENT 5
#define ERROR_LIMIT 25

class GSM {
public:
  GSM(String phoneNumber);

  boolean sendSMS(String text);
  String receiveSMS();
  
  void cosmConnect();
  void cosmSend(String feed, int t, int h, int r, int e);  
  void cosmDisconnect();
  
  boolean isAlive();
  boolean check();  
  void power();
  void init();

private:
  String _phoneNumber;
  SoftwareSerial _gprsSerial;
  int _powerPin;

  char _lastData[ANSWER_LINE_LEN+1];
  unsigned long _lastCheckSmsTs;
  boolean _smsReceived;
  
  unsigned long _lastPingTs;
  int _errorCount;
  
  int _wait(char* response, boolean crlf, long timeout);

  inline int _wait(char* response, long timeout) {
    return _wait(response, true, timeout);
  }
  
  inline int _wait(char* response) {
    return _wait(response, WAIT_TIMEOUT);
  }

  inline int _wait() {
    return _wait(NULL, WAIT_TIMEOUT);
  }

  inline int _flush() {
    return _wait(NULL, -1);
  }

  inline int _waitOk(long timeout) {
    return _wait("OK", timeout);
  }

  inline int _waitOk() {
    return _wait("OK", WAIT_TIMEOUT);
  }

  inline int _waitPrompt(long timeout) {
    return _wait(">", false, timeout);
  }

  inline int _waitPrompt() {
    return _waitPrompt(WAIT_TIMEOUT);
  }

};

#endif
